
import MarkdownIt from "markdown-it";
import { ArticleDetail } from "@/types/article";
import { queryArticleDetail } from "@/api/article.api";

import hljs from "highlight.js";
import { useSearchParams } from "react-router-dom";
import {  useEffect, useState } from "react";
// import MarkdownItToc from "markdown-it-toc";
export const useArticleRender = (): {
  article: ArticleDetail;
  articleHtml: string;
  articleToc: string;

} => {
  const [searchParams] = useSearchParams();
 
  const queryParams = searchParams.get('id');

  const [articleToc ,setArticleToc]= useState("");
  const [article,setArticle] = useState(new ArticleDetail());
  const [articleHtml,setArticleHtml] = useState("");
 

  const getArticleInfo = async (id: string) => {
    const res = await queryArticleDetail(id);
    if (res.code === 200) {
      setArticle(res.data || new ArticleDetail())
     
    }
  };
  const renderMd = () => {
    try {
      const md = new MarkdownIt({
        html: true,
        linkify: true,
        typographer: true,
        highlight: function (str: string, lang: string) {
          const language = hljs.getLanguage(lang) ? lang : "plaintext";
          // 返回分割后的数组
          // 根据换行符或回车分割成字符串数组
          const getLines = (text: string) => {
            if (text.length === 0) return [];
            return text.split(/\r\n|\r|\n/g);
          };
          const textHtml = hljs.highlight(str, { language }).value;
          const lines = getLines(textHtml);
  
          // 自定义代码块的标签节点
          let html = "";
          for (let i = 0, l = lines.length; i < l - 1; i++) {
            const text = lines[i].length > 0 ? lines[i] : " ";
            html += `<tr>
           <td class="blob-num" data-line-number="${i + 1}"></td>
           <td class="blob-code blob-code-inner">${text}</td>
         </tr>`;
          }
          return `<pre class="hljs"><code><table class="highlight" data-lang="${language}">${html}</table></code></pre>`;
          // return `<table class="highlight" data-lang="${language}">${html}</table>`;
        },
        langPrefix: "hljs language-",
        breaks: false,
        xhtml: false,
      });
      // md.use(MarkdownItToc, []);
      const mdResult = md.render(article.content);
        setArticleHtml(mdResult)
    setArticleToc( md.toc)
    } catch (error) {
      console.log(error);
      
    }
   
 
  };
  useEffect(()=>{
    const articleId = queryParams as string;
    articleId && getArticleInfo(articleId);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[])
 useEffect(()=>{
  renderMd();
 })

  return {
    article,
    articleHtml,
    articleToc,
   
  };
};
